import type { MethodWithServiceInfo } from "@linksaas-minapp/grpc-proxy-api";
import { useEffect, useState } from "react"
import { Tabs } from "antd"
import type { Tab } from "rc-tabs/lib/interface"
import { ApiOutlined } from "@ant-design/icons";
import MethodCall from "./MethodCall";
import type { GrpcServerInfo } from "@linksaas-minapp/api/extra_info";

export interface MethodCallListProps {
    grpcApiId: string;
    curMethodList: MethodWithServiceInfo[];
    grpcInfo: GrpcServerInfo;
    onClose: (method: MethodWithServiceInfo) => void;
}

function MethodCallList(props:MethodCallListProps) {
    const [tabList, setTabList] = useState<Tab[]>([]);

    const getSvcName = (name: string) => {
        const parts = name.split(".");
        if (parts.length == 2) {
            return parts[1];
        }
        return name;
    }
    
    const adjustTabList = () => {
        const newKeyList = props.curMethodList.map(item => `${item.serviceName}.${item.method.methodName}`);
        //关闭tab
        const tmpList = tabList.filter(item => newKeyList.includes(item.key));
        //新增tab
        const oldKeyList = tmpList.map(item => item.key);
        for (const method of props.curMethodList) {
            const key = `${method.serviceName}.${method.method.methodName}`;
            if (oldKeyList.includes(key)) {
                continue;
            }
            tmpList.push({
                key: key,
                label: <span title={key}><ApiOutlined />{getSvcName(method.serviceName)}:{method.method.methodName}</span>,
                children: <MethodCall grpcApiId={props.grpcApiId} method={method} grpcInfo={props.grpcInfo}/>,
            });
        }
        setTabList(tmpList);
    };
    
    useEffect(() => {
        adjustTabList();
    }, [props.curMethodList]);
    
    return (
        <Tabs type="editable-card" tabBarStyle={{ margin: "0px 0px" }}
            items={tabList} hideAdd onEdit={(targetKey, action) => {
                if (action == "remove") {
                    const method = props.curMethodList.find(item => targetKey == `${item.serviceName}.${item.method.methodName}`);
                    if (method !== undefined) {
                        props.onClose(method);
                    }
                }
            }}  />
    )
}

export default MethodCallList;